package com.ityuwen.mengyagushi.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 获取当前请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null){
            ServletRequestAttributes sra = (ServletRequestAttributes)requestAttributes;
            HttpServletRequest request = sra.getRequest();

            // 从request对象中获取token
            String token = request.getHeader("token");

            // 设置到feign请求对象中
            template.header("token", token);
        }
    }
}
